package com.thiswhyme.demo.msgpush.core.impl.websocket.event;

import com.thiswhyme.demo.msgpush.core.event.AbstractBroadcastEventHandler;
import com.thiswhyme.demo.msgpush.core.event.bean.WebSocketEvent;
import com.thiswhyme.demo.msgpush.core.impl.websocket.SessionManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.Map;

/**
 * @description: WebSocket消息广播事件处理器-ws实现
 * @author: thiswhyme
 * @date: 2021/9/28
 */
@Slf4j
public class BroadcastEventWsHandler extends AbstractBroadcastEventHandler {

    @Override
    public void doHandle(WebSocketEvent event) {
        Map<String, WebSocketSession> sessions = SessionManager.getAll();
        if (CollectionUtils.isEmpty(sessions)) {
            log.warn("该实例上没有可用的Session，跳过处理");
            return;
        }

        sessions.forEach((identifier, session) -> {
            try {
                if (null != session && session.isOpen()) {
                    session.sendMessage(new TextMessage(event.getMsgContent()));
                    log.debug("【{}】完成广播", identifier);
                } else {
                    log.error("【{}】广播失败，Session已关闭", identifier);
                }
            } catch (IOException e) {
                log.error("【{}】广播失败", identifier, e);
            }
        });
    }
}
